package com.boilermaker.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    /**
     * 为 ObjectMapper 创建单例（懒汉）
     */
    private JacksonUtil() {

    }

    private static class instanceHolder {
        private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper() {
        return instanceHolder.OBJECT_MAPPER;
    }

    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    /**
     * 在此统一进行 JacksonUtil 的异常处理，将其转化为 Spring 封装的非受查异常
     * @param parser 该回调函数真正执行序列化或反序列化方法
     * @param check 可能出现的异常
     * @return
     * @param <T>
     */
    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call(); // 回调
        } catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) { // 抛出的异常是我们所预期的
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }

    /**
     * 序列化
     *
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object) {
        return tryParse(() -> JacksonUtil.getObjectMapper().writeValueAsString(object));
    }

    /**
     * 反序列化
     *
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return tryParse(() -> JacksonUtil.getObjectMapper().readValue(content, valueType));
    }

    /**
     * 反序列化为 List
     *
     * @param content
     * @param memberType
     * @param <T>
     * @return
     */
    public static <T> T readListValue(String content, Class<?> memberType) {
        JavaType javaType = JacksonUtil.getObjectMapper().getTypeFactory().constructParametricType(
                List.class, memberType);
        return tryParse(() -> JacksonUtil.getObjectMapper().readValue(content, javaType));
    }
}
